package com.example.flex.resolver.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.flex.common.types.BusinessEnum;
import com.example.flex.domain.vo.LoginUserVO;
import com.example.flex.utils.jwt.JwtUtil;
import com.example.flex.utils.redis.RedisCache;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author: 不是菜鸡爱编程
 * @Date: 2023/11/06/20:19
 * @Description:
 */
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取请求路径
        String path = request.getServletPath();
        if("/user/login".equals(path)||"/user/register".equals(path)||"/oss/upload".equals(path)){
            log.info("jwt拦截器放行");
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String userid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            // 这里抛出的异常没有被@RestControllerAdvice捕获到从而进行异常处理，原因很简单
            // 抛出异常的代码段放在try-catch里，异常被try-catch捕获了，所以不会被@RestControllerAdvice捕获到
            throw new RuntimeException(BusinessEnum.TOKEN_IS_WRONG.getMsg());
        }
        //从redis中获取用户信息
        String redisKey = "login:" + userid;
        // 获取user
        LoginUserVO loginUser = JSON.parseObject(redisCache.getCacheObject(redisKey).toString(), LoginUserVO.class);
        if(Objects.isNull(loginUser)){
            throw new RuntimeException(BusinessEnum.USER_NOT_LOGIN.getMsg());
        }
        //存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }

    /**
     * JSONArray转List
     */
    public static List<String> jsonArrayToList(JSONArray jsonArray) {
        if(CollectionUtils.isEmpty(jsonArray)) {
            return new ArrayList<>();
        }
        return JSONObject.parseArray(jsonArray.toJSONString(), String.class);
    }
}